package com.zy.explore.license.infrastructure.util;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * <p>建类说明：命令行工具类</p>
 *
 * @author 中国印
 * @date 2022年04月07日 14:29:00
 */
public class CommandLineUtil {

    /**
     * <p>方法说明：执行windows cmd</p>
     *
     * @param cmd cmd
     */
    public static void executeWindowsCmd(String cmd) {
        if (StringUtils.isEmpty(cmd)) {
            return;
        }
        cmd = cmd.replace("/", File.separator);
        // 获取Runtime实例
        Runtime runtime = Runtime.getRuntime();
        // 执行命令
        try {
            String[] command = new String[]{"cmd", "/c", cmd};
            Process process = runtime.exec(command);
            // 标准输入流（必须写在 waitFor 之前）
            String inStr = consumeInputStream(process.getInputStream());
            // 标准错误流（必须写在 waitFor 之前）
            //若有错误信息则输出
            String errStr = consumeInputStream(process.getErrorStream());
            int proc = process.waitFor();
            if (proc == 0) {
                System.out.println("执行成功");
            } else {
                System.out.println("执行失败" + errStr);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * InputStream，并返回
     */
    private static String consumeInputStream(InputStream is) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = br.readLine()) != null) {
            System.out.println(s);
            sb.append(s);
        }
        return sb.toString();
    }


    /**
     * <p>方法说明：执行linux cmd</p>
     *
     * @param cmd cmd
     * @return boolean
     */
    public static boolean executeLinuxCmd(String cmd) {
        boolean result = false;
        Runtime run = Runtime.getRuntime();
        //InputStream in=null;
        try {
            Process process = run.exec(cmd);
            //执行结果 0 表示正常退出
            int exeResult = process.waitFor();
            if (exeResult == 0) {
                System.out.println("执行成功");
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取linux命令执行的结果,cat 之类
     *
     * @param cmd 命令
     * @return 返回结果
     */
    public static String getLinuxCmdResult(String cmd) {
        String result = "";
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null) {
                result = line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * grep 类的shell命令
     *
     * @param cmdStr 命令
     * @return 返回结果
     */
    public static String getGrepCmdReturn(String cmdStr) {
        String[] cmd = new String[3];
        cmd[0] = "/bin/sh";
        cmd[1] = "-c";
        cmd[2] = cmdStr;
        //得到Java进程的相关Runtime运行对象
        Runtime runtime = Runtime.getRuntime();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            Process process = runtime.exec(cmd);
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            stringBuilder = new StringBuilder();
            String temp;
            while ((temp = bufferReader.readLine()) != null) {
                stringBuilder.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}
